﻿using Furion;
using Furion.Schedule;
using Furion.VirtualFileServer;
using ST.Torch.WebApi.Core.Job;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Text.Json;

namespace ST.Torch.WebApi.Web.Core;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddConsoleFormatter();
        //services.AddJwt<JwtHandler>();
        //配置JWT+Cookie混合授权
        services.AddJwt<JwtHandler>(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, b =>
        {
            b.LoginPath = "/Home/Login";
            b.AccessDeniedPath = "/Home/Error403";
        });

        services.AddCorsAccessor();

        services.AddControllersWithViews()
                    .AddInjectWithUnifyResult();

        services.AddControllersWithViews()
                   .AddInjectWithUnifyResult()
                    .AddJsonOptions(options =>
                    {
                        options.JsonSerializerOptions.Converters.AddDateTimeTypeConverters("yyyy-MM-dd HH:mm:ss");//时间格式化
                                                                                                                  ////解决文档中样例参数说明中参数首字母变小写的问题
                        options.JsonSerializerOptions.PropertyNamingPolicy = null;
                    });
        services.AddSchedule(options =>
        {
            options.LogEnabled = false;
            var triggerBuilder = Triggers.PeriodHours(6).SetRunOnStart(true);
            options.AddJob<SearchJob>(concurrent: false, triggerBuilder);
        });
        //多语言
        services.AddAppLocalization();
        //远程请求服务 HttpClient
        services.AddHttpRemote();
        //试图 修改后实时刷新--Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
        //services.AddMvc().AddRazorRuntimeCompilation();
        services.AddRazorPages().AddRazorRuntimeCompilation();

        //虚拟文件
        services.AddVirtualFileServer();

        if (App.Configuration["SysInfo:Cache"] == "Redis")
        {
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = App.Configuration["SysInfo:Redis:Connect"]; //"127.0.0.1,password=123456";
                options.InstanceName = App.Configuration["SysInfo:Redis:InstanceName"]; //"furion_";
            });
        }
        //上传文件大小
        services.Configure<FormOptions>(options =>
        {
            options.ValueLengthLimit = 400 * 1024 * 1024; // 400 MB
            options.KeyLengthLimit = 400 * 1024 * 1024; // 400 MB
            options.MultipartHeadersCountLimit = 400 * 1024 * 1024; // 400 MB
            options.MultipartBodyLengthLimit = 400 * 1024 * 1024; // 400 MB
        });

        // 错误异常记录批量设置多个
        Array.ForEach(new[] { LogLevel.Information, LogLevel.Warning, LogLevel.Error }, logLevel =>
        {
            services.AddFileLogging("logs/{0:yyyy}-{0:MM}-{0:dd}/application-{1}.log", options =>
            {
                options.FileNameRule = fileName => string.Format(fileName, DateTime.UtcNow, logLevel.ToString());
                options.WriteFilter = logMsg => logMsg.LogLevel == logLevel;
            });
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        //多语言
        app.UseAppLocalization();

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseCorsAccessor();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseInject();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
			endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");

		});
    }
}
